/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import AdminOperations.AdminAddAdv;
import beans.AddAdvForm;
import beans.UserType;
import java.io.File;
import java.io.FileOutputStream;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

/**
 *
 * @author ABDELMOHSEN
 */
public class AddAdv extends org.apache.struts.action.Action {
    
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        
        UserType type=(UserType)request.getSession().getAttribute("type");
        if(type==null||!type.equals(UserType.adm)) return mapping.findForward("login");
        AddAdvForm bean=(AddAdvForm)form;
        if(bean.getImg()==null||bean.getUrl()==null||bean.getImg().getFileSize()==0||bean.getUrl().length()==0) {
            request.getSession().setAttribute("mesg", "Required data not entered");
            return mapping.findForward("failed");
        }
        FormFile formFile=bean.getImg();
        FileOutputStream outputStream = null;
        String path = getServlet().getServletContext().getRealPath("") + "/imgad.png";
        outputStream = new FileOutputStream(new File(path));
        outputStream.write(formFile.getFileData());
        outputStream.close();
        String URL=bean.getUrl();
        if(!URL.contains("http")){
            URL="http://"+URL;
        }
        AdminAddAdv model=new AdminAddAdv();
        model.addAdv(URL);
        ServletContext context=getServlet().getServletConfig().getServletContext();
        context.setAttribute("url",URL);
        return mapping.findForward("done");
    }
}
